{% extends 'base.html' %}

{% load static %}

{% block title %}{{ stock.name }} - 股票详情{% endblock %}

{% block extra_css %}
<style>
    .stock-price {
        font-size: 32px;
        font-weight: bold;
        transition: all 0.3s ease;
    }

    .price-up {
        color: #ff5252;
        text-shadow: 0 0 10px rgba(255, 82, 82, 0.2);
    }

    .price-down {
        color: #4caf50;
        text-shadow: 0 0 10px rgba(76, 175, 80, 0.2);
    }

    .price-unchanged {
        color: #7f8c8d;
    }

    .stock-change {
        font-size: 18px;
        margin-left: 10px;
        font-weight: 500;
    }

    .chart-container {
        height: 400px;
        margin-bottom: 20px;
        border-radius: 1rem;
        box-shadow: 0 8px 25px rgba(0,0,0,0.07);
        background-color: white;
        overflow: hidden;
        transition: all 0.3s ease;
    }

    .chart-container:hover {
        box-shadow: 0 15px 35px rgba(0,0,0,0.1);
    }

    .chart-tabs {
        display: flex;
        margin-bottom: 10px;
        border-bottom: 1px solid #e8e8e8;
    }

    .chart-tab {
        padding: 8px 16px;
        margin-right: 8px;
        background: none;
        border: none;
        cursor: pointer;
        outline: none;
        font-size: 14px;
        color: #595959;
    }

    .chart-tab.active {
        color: #1890ff;
        border-bottom: 2px solid #1890ff;
    }

    .chart-container {
        margin-bottom: 20px;
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
        padding: 16px;
    }

    .breadcrumb {
        background-color: rgba(255, 255, 255, 0.6);
        padding: 0.75rem 1rem;
        border-radius: 0.5rem;
        box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }

    .breadcrumb-item a {
        color: var(--primary-color);
        text-decoration: none;
        font-weight: 500;
        transition: all 0.3s ease;
    }

    .breadcrumb-item a:hover {
        color: var(--secondary-color);
    }

    .loading {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 300px;
        flex-direction: column;
    }

    .loading .spinner-border {
        width: 3rem;
        height: 3rem;
        margin-bottom: 1rem;
    }

    .table-responsive {
        border-radius: 0.5rem;
        overflow: hidden;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="/">首页</a></li>
                    <li class="breadcrumb-item"><a href="/stocks/">股票行情</a></li>
                    <li class="breadcrumb-item active">{{ stock.name }} ({{ stock.code }})</li>
                </ol>
            </nav>
        </div>
    </div>

    <!-- 基本信息卡片 -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card shadow-sm stock-info-card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="bi bi-info-circle"></i> {{ stock.name }} ({{ stock.code }}) 基本信息</h5>
                </div>
                <div class="card-body">
                    {% if latest_data %}
                    <div class="stock-price {% if change_percent > 0 %}price-up{% elif change_percent < 0 %}price-down{% else %}price-unchanged{% endif %}">
                        {{ latest_data.current_price }}
                        <span class="stock-change">
                            {{ change|floatformat:2 }} ({{ change_percent|floatformat:2 }}%)
                        </span>
                    </div>
                    <div class="mt-3">
                        <div class="row">
                            <div class="col-6">
                                <p class="mb-1">开盘价: {{ latest_data.open_price }}</p>
                                <p class="mb-1">最低价: {{ latest_data.low_price }}</p>
                            </div>
                            <div class="col-6">
                                <p class="mb-1">昨收价: {{ latest_data.last_close }}</p>
                                <p class="mb-1">成交量: {{ latest_data.volume }} 手</p>
                            </div>
                        </div>
                    </div>
                    {% else %}
                    <p>无最新数据</p>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- 图表卡片 -->
    <div class="card shadow-sm mb-4">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="bi bi-graph-up"></i> 技术分析图表</h5>
        </div>
        <div class="card-body">
            <!-- 图表切换标签 -->
            <div class="chart-tabs">
                <button id="k-chart-tab" class="chart-tab active">K线图</button>
                <button id="minute-chart-tab" class="chart-tab">分时图</button>
                <button class="chart-tab" onclick="showChart('macd')">MACD</button>
                <button class="chart-tab" onclick="showChart('rsi')">RSI</button>
                <button class="chart-tab" onclick="showChart('bollinger')">布林带</button>
                <button class="chart-tab" onclick="showChart('ma')">均线</button>
            </div>

            <!-- K线图容器 -->
            <div id="k-chart-container" class="chart-container">
                <div id="loading" class="loading">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                </div>
                <div id="chart-container" style="width: 100%; height: 500px;"></div>
            </div>

            <!-- 分时图容器 -->
            <div id="minute-chart-container" class="chart-container" style="display: none;">
                <div id="minute-chart" style="width: 100%; height: 400px;"></div>
            </div>

            <!-- 其他技术指标图表容器 -->
            <div id="macd-chart" class="chart-container" style="display: none; width: 100%; height: 500px;"></div>
            <div id="rsi-chart" class="chart-container" style="display: none; width: 100%; height: 500px;"></div>
            <div id="bollinger-chart" class="chart-container" style="display: none; width: 100%; height: 500px;"></div>
            <div id="ma-chart" class="chart-container" style="display: none; width: 100%; height: 500px;"></div>
        </div>
    </div>

    <!-- 历史数据表格 -->
    <div class="card shadow-sm mb-4">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="bi bi-table"></i> 历史数据</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-striped table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>日期</th>
                            <th>开盘价</th>
                            <th>收盘价</th>
                            <th>最高价</th>
                            <th>最低价</th>
                            <th>成交量(手)</th>
                            <th>成交额(元)</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for index, row in history_data.iterrows %}
                        <tr>
                            <td>{{ row.date|date:"Y-m-d" }}</td>
                            <td>{{ row.open_price }}</td>
                            <td>{{ row.close_price }}</td>
                            <td>{{ row.high_price }}</td>
                            <td>{{ row.low_price }}</td>
                            <td>{{ row.volume }}</td>
                            <td>{{ row.amount }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}

*<!-- 直接添加 CSS 和 JS 文件的路径 -->*

<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'css/bootstrap-icons.css' %}">
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<script src="{% static 'js/bootstrap.bundle.min.js' %}"></script>
<script src="{% static 'js/echarts.min.js' %}"></script>

<script>
    // 从Django模板获取数据
    const chartData = {{ chart_data|safe }};

    // 准备K线图数据
    const dates = chartData.dates;
    const data = dates.map((date, index) => [
        date,
        chartData.open[index],
        chartData.close[index],
        chartData.low[index],
        chartData.high[index],
        chartData.volume[index]
    ]);

    // 初始化图表
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('loading').style.display = 'flex';

        setTimeout(function() {
            document.getElementById('loading').style.display = 'none';
            document.getElementById('k-chart-container').style.display = 'block';

            // 初始化K线图
            const candlestickChart = echarts.init(document.getElementById('chart-container'));
            const candlestickOption = {
                title: {
                    text: '{{ stock.name }} K线图',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    },
                    formatter: function(params) {
                        const param = params[0];
                        return `${param.name}<br/>
                            开盘价: ${param.data[1]}<br/>
                            收盘价: ${param.data[2]}<br/>
                            最低价: ${param.data[3]}<br/>
                            最高价: ${param.data[4]}<br/>
                            成交量: ${param.data[5]} 手`;
                    }
                },
                legend: {
                    data: ['K线', '成交量'],
                    bottom: 10
                },
                grid: [
                    {
                        left: '10%',
                        right: '10%',
                        height: '60%'
                    },
                    {
                        left: '10%',
                        right: '10%',
                        top: '75%',
                        height: '15%'
                    }
                ],
                xAxis: [
                    {
                        type: 'category',
                        data: dates,
                        scale: true,
                        boundaryGap: false,
                        axisLine: {onZero: false},
                        splitLine: {show: false},
                        splitNumber: 20,
                        min: 'dataMin',
                        max: 'dataMax'
                    },
                    {
                        type: 'category',
                        gridIndex: 1,
                        data: dates,
                        scale: true,
                        boundaryGap: false,
                        axisLine: {onZero: false},
                        axisTick: {show: false},
                        splitLine: {show: false},
                        axisLabel: {show: false},
                        splitNumber: 20,
                        min: 'dataMin',
                        max: 'dataMax'
                    }
                ],
                yAxis: [
                    {
                        scale: true,
                        splitArea: {
                            show: true
                        }
                    },
                    {
                        scale: true,
                        gridIndex: 1,
                        splitNumber: 2,
                        axisLabel: {show: false},
                        axisLine: {show: false},
                        axisTick: {show: false},
                        splitLine: {show: false}
                    }
                ],
                dataZoom: [
                    {
                        type: 'inside',
                        xAxisIndex: [0, 1],
                        start: 50,
                        end: 100
                    },
                    {
                        show: true,
                        xAxisIndex: [0, 1],
                        type: 'slider',
                        top: '92%',
                        start: 50,
                        end: 100
                    }
                ],
                series: [
                    {
                        name: 'K线',
                        type: 'candlestick',
                        data: data.map(item => [item[1], item[2], item[3], item[4]]),
                        itemStyle: {
                            // 红涨绿跌
                            color: '#e74c3c',
                            color0: '#2ecc71',
                            borderColor: '#e74c3c',
                            borderColor0: '#2ecc71'
                        },
                        markPoint: {
                            data: [
                                {type: 'max', name: '最高值', valueDim: 'highest'},
                                {type: 'min', name: '最低值', valueDim: 'lowest'}
                            ]
                        }
                    },
                    {
                        name: '成交量',
                        type: 'bar',
                        xAxisIndex: 1,
                        yAxisIndex: 1,
                        data: data.map(item => item[5]),
                        itemStyle: {
                            color: function(params) {
                                const i = params.dataIndex;
                                return data[i][1] <= data[i][2] ? '#e74c3c' : '#2ecc71';
                            }
                        }
                    }
                ],
                animation: true,
                animationDuration: 1000,
                animationEasing: 'elasticOut'
            };

            // 使用动画绘制K线图
            candlestickChart.setOption(candlestickOption);

            // 初始化其他图表
            initializeOtherCharts();

            // 响应窗口大小变化
            window.addEventListener('resize', function() {
                candlestickChart.resize();
                if (window.macdChart) window.macdChart.resize();
                if (window.rsiChart) window.rsiChart.resize();
                if (window.bollingerChart) window.bollingerChart.resize();
                if (window.maChart) window.maChart.resize();
            });
        }, 1000);
    });

    // 切换图表
    function showChart(chartType) {
        document.querySelectorAll('.chart-tab').forEach(tab => {
            tab.classList.remove('active');
        });

        if (chartType === 'k-chart') {
            document.getElementById('k-chart-tab').classList.add('active');
            document.getElementById('k-chart-container').style.display = 'block';
            document.getElementById('minute-chart-container').style.display = 'none';
            document.getElementById('macd-chart').style.display = 'none';
            document.getElementById('rsi-chart').style.display = 'none';
            document.getElementById('bollinger-chart').style.display = 'none';
            document.getElementById('ma-chart').style.display = 'none';
        } else if (chartType === 'minute') {
            document.getElementById('minute-chart-tab').classList.add('active');
            document.getElementById('k-chart-container').style.display = 'none';
            document.getElementById('minute-chart-container').style.display = 'block';
            document.getElementById('macd-chart').style.display = 'none';
            document.getElementById('rsi-chart').style.display = 'none';
            document.getElementById('bollinger-chart').style.display = 'none';
            document.getElementById('ma-chart').style.display = 'none';

            // 初始化分时图
            if (!minuteChart) {
                initMinuteChart();
            }
        } else {
            document.querySelector(`.chart-tab[onclick="showChart('${chartType}')"]`).classList.add('active');
            document.getElementById('k-chart-container').style.display = 'none';
            document.getElementById('minute-chart-container').style.display = 'none';
            document.getElementById(`${chartType}-chart`).style.display = 'block';
            document.getElementById('macd-chart').style.display = chartType === 'macd' ? 'block' : 'none';
            document.getElementById('rsi-chart').style.display = chartType === 'rsi' ? 'block' : 'none';
            document.getElementById('bollinger-chart').style.display = chartType === 'bollinger' ? 'block' : 'none';
            document.getElementById('ma-chart').style.display = chartType === 'ma' ? 'block' : 'none';
        }

        // 确保图表正确调整大小
        if (chartType === 'macd' && window.macdChart) window.macdChart.resize();
        if (chartType === 'rsi' && window.rsiChart) window.rsiChart.resize();
        if (chartType === 'bollinger' && window.bollingerChart) window.bollingerChart.resize();
        if (chartType === 'ma' && window.maChart) window.maChart.resize();
    }

    // 初始化其他图表
    function initializeOtherCharts() {
        // 初始化MACD图
        const macdChart = echarts.init(document.getElementById('macd-chart'));
        window.macdChart = macdChart;
        // 计算MACD指标
        calculateMACD(chartData.close, macdChart);

        // 初始化RSI图
        const rsiChart = echarts.init(document.getElementById('rsi-chart'));
        window.rsiChart = rsiChart;
        // 计算RSI指标
        calculateRSI(chartData.close, rsiChart);

        // 初始化布林带图
        const bollingerChart = echarts.init(document.getElementById('bollinger-chart'));
        window.bollingerChart = bollingerChart;
        // 计算布林带
        calculateBollinger(chartData.close, chartData.dates, bollingerChart);

        // 初始化均线图
        const maChart = echarts.init(document.getElementById('ma-chart'));
        window.maChart = maChart;
        // 计算均线
        calculateMA(chartData.close, chartData.dates, maChart);
    }

    // 计算MACD
    function calculateMACD(closeData, chart) {
        const ema12 = [];
        const ema26 = [];
        const diff = [];
        const dea = [];
        const macd = [];

        // 计算EMA
        let k1 = 2 / (12 + 1);
        let k2 = 2 / (26 + 1);
        let k3 = 2 / (9 + 1);

        ema12[0] = closeData[0];
        ema26[0] = closeData[0];

        for (let i = 1; i < closeData.length; i++) {
            ema12[i] = ema12[i-1] * (1 - k1) + closeData[i] * k1;
            ema26[i] = ema26[i-1] * (1 - k2) + closeData[i] * k2;
        }

        for (let i = 0; i < closeData.length; i++) {
            diff[i] = ema12[i] - ema26[i];
        }

        dea[0] = diff[0];
        for (let i = 1; i < closeData.length; i++) {
            dea[i] = dea[i-1] * (1 - k3) + diff[i] * k3;
        }

        for (let i = 0; i < closeData.length; i++) {
            macd[i] = (diff[i] - dea[i]) * 2;
        }

        const option = {
            title: {
                text: 'MACD指标',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            legend: {
                data: ['DIFF', 'DEA', 'MACD'],
                bottom: 10
            },
            xAxis: {
                type: 'category',
                data: chartData.dates,
                scale: true,
                boundaryGap: false,
                axisLine: {onZero: false},
                splitLine: {show: false},
                splitNumber: 20,
                min: 'dataMin',
                max: 'dataMax'
            },
            yAxis: {
                scale: true,
                splitArea: {
                    show: true
                }
            },
            dataZoom: [
                {
                    type: 'inside',
                    start: 50,
                    end: 100
                },
                {
                    show: true,
                    type: 'slider',
                    bottom: 60,
                    start: 50,
                    end: 100
                }
            ],
            series: [
                {
                    name: 'DIFF',
                    type: 'line',
                    data: diff,
                    smooth: true,
                    lineStyle: {
                        color: '#c23531',
                        width: 2
                    }
                },
                {
                    name: 'DEA',
                    type: 'line',
                    data: dea,
                    smooth: true,
                    lineStyle: {
                        color: '#2f4554',
                        width: 2
                    }
                },
                {
                    name: 'MACD',
                    type: 'bar',
                    data: macd,
                    itemStyle: {
                        color: function(params) {
                            return params.data >= 0 ? '#e74c3c' : '#2ecc71';
                        }
                    }
                }
            ],
            animation: true,
            animationDuration: 1000,
            animationEasing: 'elasticOut'
        };

        chart.setOption(option);
    }

    // 计算RSI
    function calculateRSI(closeData, chart) {
        const periods = 14;
        const rsi = [];
        let gain = 0;
        let loss = 0;

        for (let i = 1; i < periods + 1; i++) {
            const diff = closeData[i] - closeData[i-1];
            if (diff >= 0) {
                gain += diff;
            } else {
                loss -= diff;
            }
        }

        let avgGain = gain / periods;
        let avgLoss = loss / periods;
        let rs = avgGain / avgLoss;
        rsi[periods] = 100 - (100 / (1 + rs));

        for (let i = periods + 1; i < closeData.length; i++) {
            const diff = closeData[i] - closeData[i-1];
            let currentGain = 0;
            let currentLoss = 0;

            if (diff >= 0) {
                currentGain = diff;
            } else {
                currentLoss = -diff;
            }

            avgGain = (avgGain * (periods - 1) + currentGain) / periods;
            avgLoss = (avgLoss * (periods - 1) + currentLoss) / periods;
            rs = avgGain / avgLoss;
            rsi[i] = 100 - (100 / (1 + rs));
        }

        // 填充前面的空值
        for (let i = 0; i < periods; i++) {
            rsi[i] = null;
        }

        const option = {
            title: {
                text: 'RSI指标(14天)',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis'
            },
            xAxis: {
                type: 'category',
                data: chartData.dates,
                scale: true,
                boundaryGap: false
            },
            yAxis: {
                min: 0,
                max: 100,
                splitLine: {
                    show: true
                },
                axisLabel: {
                    formatter: '{value}%'
                }
            },
            dataZoom: [
                {
                    type: 'inside',
                    start: 50,
                    end: 100
                },
                {
                    show: true,
                    type: 'slider',
                    bottom: 60,
                    start: 50,
                    end: 100
                }
            ],
            series: [
                {
                    name: 'RSI',
                    type: 'line',
                    data: rsi,
                    smooth: true,
                    markLine: {
                        data: [
                            {
                                yAxis: 70,
                                lineStyle: { color: '#e74c3c', type: 'dashed' }
                            },
                            {
                                yAxis: 30,
                                lineStyle: { color: '#2ecc71', type: 'dashed' }
                            }
                        ]
                    }
                }
            ],
            animation: true,
            animationDuration: 1000,
            animationEasing: 'elasticOut'
        };

        chart.setOption(option);
    }

    // 计算布林带
    function calculateBollinger(closeData, dates, chart) {
        const period = 20;
        const multiplier = 2;
        const sma = [];
        const upper = [];
        const lower = [];

        // 计算SMA和标准差
        for (let i = period - 1; i < closeData.length; i++) {
            let sum = 0;
            for (let j = 0; j < period; j++) {
                sum += closeData[i - j];
            }
            sma[i] = sum / period;

            let squaredDiffSum = 0;
            for (let j = 0; j < period; j++) {
                squaredDiffSum += Math.pow(closeData[i - j] - sma[i], 2);
            }

            const stdDev = Math.sqrt(squaredDiffSum / period);
            upper[i] = sma[i] + (multiplier * stdDev);
            lower[i] = sma[i] - (multiplier * stdDev);
        }

        // 填充前面的空值
        for (let i = 0; i < period - 1; i++) {
            sma[i] = null;
            upper[i] = null;
            lower[i] = null;
        }

        const option = {
            title: {
                text: '布林带(20,2)',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['价格', '上轨', '中轨', '下轨'],
                bottom: 10
            },
            xAxis: {
                type: 'category',
                data: dates,
                scale: true,
                boundaryGap: false
            },
            yAxis: {
                scale: true,
                splitArea: {
                    show: true
                }
            },
            dataZoom: [
                {
                    type: 'inside',
                    start: 50,
                    end: 100
                },
                {
                    show: true,
                    type: 'slider',
                    bottom: 60,
                    start: 50,
                    end: 100
                }
            ],
            series: [
                {
                    name: '价格',
                    type: 'line',
                    data: closeData,
                    smooth: true,
                    z: 3
                },
                {
                    name: '上轨',
                    type: 'line',
                    data: upper,
                    smooth: true,
                    lineStyle: {
                        color: '#e74c3c',
                        type: 'dashed'
                    },
                    z: 2
                },
                {
                    name: '中轨',
                    type: 'line',
                    data: sma,
                    smooth: true,
                    lineStyle: {
                        color: '#3498db'
                    },
                    z: 2
                },
                {
                    name: '下轨',
                    type: 'line',
                    data: lower,
                    smooth: true,
                    lineStyle: {
                        color: '#2ecc71',
                        type: 'dashed'
                    },
                    z: 2
                }
            ],
            animation: true,
            animationDuration: 1000,
            animationEasing: 'elasticOut'
        };

        chart.setOption(option);
    }

    // 计算均线
    function calculateMA(closeData, dates, chart) {
        const calcMA = function(data, dayCount) {
            const result = [];
            for (let i = 0; i < data.length; i++) {
                if (i < dayCount - 1) {
                    result.push(null);
                    continue;
                }
                let sum = 0;
                for (let j = 0; j < dayCount; j++) {
                    sum += data[i - j];
                }
                result.push(+(sum / dayCount).toFixed(2));
            }
            return result;
        };

        const ma5 = calcMA(closeData, 5);
        const ma10 = calcMA(closeData, 10);
        const ma20 = calcMA(closeData, 20);
        const ma60 = calcMA(closeData, 60);

        const option = {
            title: {
                text: '均线图',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['价格', 'MA5', 'MA10', 'MA20', 'MA60'],
                bottom: 10
            },
            xAxis: {
                type: 'category',
                data: dates,
                scale: true,
                boundaryGap: false
            },
            yAxis: {
                scale: true,
                splitArea: {
                    show: true
                }
            },
            dataZoom: [
                {
                    type: 'inside',
                    start: 50,
                    end: 100
                },
                {
                    show: true,
                    type: 'slider',
                    bottom: 60,
                    start: 50,
                    end: 100
                }
            ],
            series: [
                {
                    name: '价格',
                    type: 'line',
                    data: closeData,
                    smooth: true,
                    z: 5
                },
                {
                    name: 'MA5',
                    type: 'line',
                    data: ma5,
                    smooth: true,
                    lineStyle: {
                        color: '#e74c3c'
                    },
                    z: 4
                },
                {
                    name: 'MA10',
                    type: 'line',
                    data: ma10,
                    smooth: true,
                    lineStyle: {
                        color: '#3498db'
                    },
                    z: 3
                },
                {
                    name: 'MA20',
                    type: 'line',
                    data: ma20,
                    smooth: true,
                    lineStyle: {
                        color: '#2ecc71'
                    },
                    z: 2
                },
                {
                    name: 'MA60',
                    type: 'line',
                    data: ma60,
                    smooth: true,
                    lineStyle: {
                        color: '#9b59b6'
                    },
                    z: 1
                }
            ],
            animation: true,
            animationDuration: 1000,
            animationEasing: 'elasticOut'
        };

        chart.setOption(option);
    }
</script>

<!-- 添加分时图脚本 -->
<script>
    // 初始化图表
    let minuteChart = null;
    let updateTimer = null;

    // 为选项卡添加点击事件
    document.getElementById('k-chart-tab').addEventListener('click', function() {
        showChart('k-chart');
    });

    document.getElementById('minute-chart-tab').addEventListener('click', function() {
        showChart('minute');
    });

    function initMinuteChart() {
        // 创建ECharts实例
        minuteChart = echarts.init(document.getElementById('minute-chart'));

        // 加载数据并初始化图表
        loadMinuteData();

        // 定时更新数据
        updateTimer = setInterval(loadMinuteData, 5000);
    }

    function loadMinuteData() {
        // 获取股票代码
        const stockCode = '{{ stock.code }}';

        // 从API获取分时数据
        fetch(`/api/stocks/${stockCode}/realtime/`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    updateMinuteChart(data.data);
                } else {
                    console.error('获取分时数据失败:', data.message);
                }
            })
            .catch(error => {
                console.error('请求分时数据出错:', error);
            });
    }

    function updateMinuteChart(data) {
        // 设置分时图选项
        const times = data.times;
        const prices = data.prices;
        const volumes = data.volumes;
        const prevClose = data.prev_close;

        // 计算涨跌幅
        const changePercent = prices.map(price => {
            return ((price - prevClose) / prevClose * 100).toFixed(2);
        });

        // 设置图表的选项及数据
        const option = {
            title: {
                text: '{{ stock.name }} 分时图',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                },
                formatter: function(params) {
                    // 确保参数顺序匹配series的顺序
                    // 第一个参数是价格线，第二个参数是成交量柱
                    const priceParams = params.find(param => param.seriesName === '价格');
                    const volumeParams = params.find(param => param.seriesName === '成交量');

                    // 安全获取值
                    const time = params[0].axisValue;
                    const price = priceParams ? priceParams.value : 0;
                    const volume = volumeParams ? volumeParams.value : 0;

                    const change = (price - prevClose).toFixed(2);
                    const percent = ((price - prevClose) / prevClose * 100).toFixed(2);

                    return `
                        <div style="font-weight:bold;margin-bottom:5px;">${time}</div>
                        <div>价格: ${price}元</div>
                        <div>涨跌: ${change}元 (${percent}%)</div>
                        <div>成交量: ${volume}手</div>
                    `;
                }
            },
            axisPointer: {
                link: {xAxisIndex: 'all'},
                label: {
                    backgroundColor: '#777'
                }
            },
            grid: [{
                left: '5%',
                right: '3%',
                top: '60px',
                height: '55%'
            }, {
                left: '5%',
                right: '3%',
                top: '75%',
                height: '15%'
            }],
            xAxis: [{
                type: 'category',
                data: times,
                boundaryGap: false,
                axisLine: {onZero: false},
                splitLine: {show: false},
                min: 'dataMin',
                max: 'dataMax',
                axisPointer: {
                    show: true
                }
            }, {
                type: 'category',
                gridIndex: 1,
                data: times,
                boundaryGap: false,
                axisLine: {onZero: false},
                splitLine: {show: false},
                axisLabel: {show: false},
                min: 'dataMin',
                max: 'dataMax'
            }],
            yAxis: [{
                scale: true,
                splitArea: {
                    show: true
                },
                axisLabel: {
                    show: true,
                    margin: 10
                }
            }, {
                scale: true,
                gridIndex: 1,
                splitNumber: 2,
                axisLabel: {show: false},
                axisLine: {show: false},
                axisTick: {show: false},
                splitLine: {show: false}
            }],
            dataZoom: [{
                type: 'inside',
                xAxisIndex: [0, 1],
                start: 0,
                end: 100
            }],
            series: [{
                name: '价格',
                type: 'line',
                data: prices,
                smooth: true,
                symbol: 'none',
                lineStyle: {
                    width: 2,
                    color: prices[prices.length - 1] >= prevClose ? '#ff4d4f' : '#52c41a'
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: prices[prices.length - 1] >= prevClose ? 'rgba(255,77,79,0.3)' : 'rgba(82,196,26,0.3)'
                    }, {
                        offset: 1,
                        color: 'rgba(250,250,250,0.1)'
                    }])
                },
                markLine: {
                    symbol: ['none', 'none'],
                    silent: true,
                    lineStyle: {
                        color: '#aaa',
                        type: 'dashed'
                    },
                    data: [
                        {yAxis: prevClose, name: '昨收'}
                    ],
                    label: {
                        show: true,
                        formatter: '昨收: ' + prevClose
                    }
                }
            }, {
                name: '成交量',
                type: 'bar',
                xAxisIndex: 1,
                yAxisIndex: 1,
                data: volumes,
                itemStyle: {
                    color: function(params) {
                        const idx = params.dataIndex;
                        // 根据价格变化来确定成交量柱状图颜色
                        if (idx > 0 && prices[idx] > prices[idx - 1]) {
                            return '#ff4d4f';  // 价格上涨，成交量为红色
                        } else {
                            return '#52c41a';  // 价格下跌，成交量为绿色
                        }
                    }
                }
            }]
        };

        // 渲染图表
        minuteChart.setOption(option);
    }

    // 在window尺寸变化时，重新调整图表大小
    window.addEventListener('resize', function() {
        if (minuteChart) {
            minuteChart.resize();
        }
    });

    // 在页面卸载时清除定时器
    window.addEventListener('beforeunload', function() {
        if (updateTimer) {
            clearInterval(updateTimer);
        }
    });
</script>
{% endblock %}